package chen.web.event.method;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public abstract class ProxyHandler implements InvocationHandler{

	protected Object object;
	private Object objectProxy;
	
	public ProxyHandler(Object object){
		this.object = object;
		objectProxy = (Object)Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this);
	}
	
	public Object getProxyObject(){
		return objectProxy;
	}
	

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		Result result = before(method, args);
		if(result == null){
			result = new Result();
		}
		
		//方法调用前如果有返回值，则直接返回
		if(result.hasReturnValue()){
			return result.getReturnValue();
		}
		
		Object returnValue = null;
		try {
			returnValue = method.invoke(object, args);
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			exception(method, args);
			throw e.getTargetException();
		}
		result.setReturnValue(returnValue);
		
		//方法调用后如果有返回值，则返回此值
		Result newResult = after(method, args, result);
		if(newResult != null && result.hasReturnValue()){
			return result.getReturnValue();
		}
		
		return returnValue;
	}

	protected abstract Result before(Method method, Object[] args);
	protected abstract Result after(Method method, Object[] args, Result result);
	protected abstract void exception(Method method, Object[] args);
}
